<script setup lang="ts">
/**
 * 接口部分
 * 1.总路由接口
 * 2.当前页数据接口
 */
/**
 * 功能部分
 * 1.模板选则
 * 2.通用跨页面widget
 */

defineOptions({
  name: "TemplatePage"
});
import { onMounted, ref, watch, type Ref, computed, nextTick, onBeforeMount, provide, onUnmounted } from "vue";
import buildTemplate from "./pages/buildTemplate.vue";
import floorTemplate from "./pages/floorTemplate.vue";
import monitorTemplate from "./pages/monitorTemplate.vue";

import Breadcrumb from "./component/Breadcrumb.vue";
import RouterTree from "./component/RouterTree.vue";
import TimelinePlayer from "./component/TimelinePlayer.vue";
import MonitorDialog from "./component/MonitorDialog.vue";

import { useRouter } from "vue-router";
import { useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

import {
  queryFactoryData,
  queryBuildData,
  queryFloorData,
  queryRoomData,
  queryTemplData,
  queryVisualTree,
  queryEqpId,
  visualqueryById,
  alarmRoomCount,
  queryAttrsByEqpIds,
  queryErcAlarmLatestList,
  queryTempAndHumid,
  queryInspectionList,
  queryInspectionItem
} from "@/api/visual/visualConfig";
import { downloadPic } from "@visual/api/api";

import { flattenDataByKeys, ensurePngSuffix, eventBus, isExcluded, isObjEmpty, start, end, setItem, getItem, carbon } from "./utils";
import { PxMessage } from "px-ui";

import useWebSocket from "@/hooks/useWs";

import { compMap } from "../assets/componentMap";
import componentList from "@visual/custom-component/component-list";
import { cloneDeep } from "@pureadmin/utils";

start();
const modules = {
  BUILD: floorTemplate,
  FLOOR: floorTemplate,
  FAC: buildTemplate,
  MONITOR: monitorTemplate
};

const leftComp: Ref<any[]> = ref([]);
const middleComp: Ref<any[]> = ref([]);
const bottomComp: Ref<any[]> = ref([]);
const widgetVerticalComp: Ref<any[]> = ref([]);
const widgetVerticalCompLeft: Ref<any[]> = ref([]);
const widgetHorizontalComp: Ref<any[]> = ref([]);
const rightComp: Ref<any[]> = ref([]);
const queryData = ref();
const flattenData = ref();
const flattenByIdData = ref();
const treeData = ref({});
let isTreeQuery = false;
const positionCode = ref("");
const flattenTreeData = ref({});
const routerTreeData = ref([]);
const pageType = ref("FAC");
const toggleTree = ref(false);
const eqpStatusStat = ref({});
const facCode = ref(localStorage.getItem("facCode"));
let globalClassName = JSON.parse(localStorage.getItem("classList"));
const className = ref("");
const setClassName = name => (className.value = name);
const alarmRoomCounts = ref(null);
const sensorRoomVal = ref(null);
const tempAndHumidSource = ref(null);
const showAttrsInRoom = ref({});
const done = ref(false);
const pipeName = ref("");
const setPipeName = name => (pipeName.value = name);
if (globalClassName?.length > 0) {
  const res = [];
  globalClassName.forEach(item => {
    res.push(item.code);
  });
  globalClassName = res;
}
const preview = ref(null);
const props = defineProps(["twinId", "isPreview", "type"]);

let middleTmp = []; //临时存放属于middle组件，因为这些组件有权限控制

const inspectionList = ref([]);
const isInspection = ref(false);

const player = ref();
const cameraItem = ref(null);
//  { name: "Intro", duration: 4 ,twinId:''},
const segments = ref([]);
const monitorPlayTime = ref(60);
const monitorDialogShow = ref(false);
const comImageList = ref({});
const comImageReady = ref(false);
const groupNameArr = ref({});

const scale = ref(1);

const curInspectionIndex = ref(0); //巡检强刷组件
const isInspectionEmpty = ref(false);
provide("eqpStatusStat", eqpStatusStat);
provide("positionCode", positionCode);
provide("pageType", pageType);
provide("facCode", facCode);
provide("curTreeData", flattenTreeData);
provide("className", { className, setClassName });
provide("alarmRoomCounts", alarmRoomCounts);
provide("showAttrsInRoom", showAttrsInRoom);
provide("middleComp", middleComp);
provide("rightComp", rightComp);
provide("globalClassName", globalClassName);
provide("pipeName", { pipeName, setPipeName });
provide("sensorRoomVal", sensorRoomVal);
provide("tempAndHumidSource", tempAndHumidSource);
provide("isInspection", isInspection);
provide("comImageList", comImageList);
provide("groupNameArr", groupNameArr);

provide("scale", scale);
provide("updateScale", updateScale);

setTimeout(() => {
  if (!done.value) {
    console.log("处理loading不消失问题");
    done.value = true;
  }
}, 7000);
watch(done, val => {
  if (val) end();
});
watch(
  () => route.query.compEmitData,
  async (newVal, oldVal) => {
    if (props.isPreview) return;
    const { routeCode } = route.query;

    if (routeCode) {
      dealInspection(routeCode);
      return;
    }
    if (newVal && newVal !== oldVal) {
      positionCode.value = newVal as string;
    } else if (!newVal) {
      positionCode.value = facCode.value;
    }
    if (!isTreeQuery) {
      isTreeQuery = true;
      queryAllTree();
    }
    getCompData({ positionCode: positionCode.value, type: route.query.type });
    try {
      useWebSocket({
        queryStr: `ws/twin`,
        needRepeat: true, //需要多次建立
        onmessage: wsCallback
      });
    } catch (e) {
      console.error(e);
    }

    preview.value = route.query.preview;
  },
  {
    immediate: true
  }
);
watch(
  () => props.twinId,
  async newVal => {
    if (newVal) {
      positionCode.value = newVal as string;
      preview.value = props.isPreview;
      done.value = true;
      if (!isTreeQuery) {
        isTreeQuery = true;
        queryAllTree();
      }
      getCompData({ positionCode: positionCode.value, type: props.type });
      try {
        useWebSocket({
          queryStr: `ws/twin`,
          needRepeat: true, //需要多次建立
          onmessage: wsCallback
        });
      } catch (e) {
        console.error(e);
      }
    }
  },
  { immediate: true }
);
const stopWatch = watch([flattenTreeData, flattenData, positionCode], () => {
  if (!isObjEmpty(flattenTreeData.value) && !isObjEmpty(flattenData.value) && positionCode.value) {
    stopWatch();
    dealDotAttrsShowInRoom(flattenTreeData.value);
    dealGroupByName(flattenTreeData.value);
  }
});

function dealGroupByName(flattenTreeData = {}) {
  let groupMap = {};
  let curData = flattenTreeData[positionCode.value];
  if (curData && curData.children) {
    for (let i = 0; i < curData.children.length; i++) {
      let item = curData.children[i];
      const { groupName, code } = item;
      if (groupName) {
        groupMap[code] = groupName;
        if (!groupNameArr.value[groupName]) groupNameArr.value[groupName] = [];
        groupNameArr.value[groupName].push(code);
      }
    }
    try {
      if (flattenData.value["eqpStatusStat"]) {
        const { children } = flattenData.value["eqpStatusStat"];
        if (children && children.length > 0) {
          children.forEach(el => {
            const { eqpId } = el;
            const groupName = groupMap[eqpId];
            if (groupName) {
              if (!eqpStatusStat.value[groupName]) eqpStatusStat.value[groupName] = [];
              eqpStatusStat.value[groupName].push(el);
            } else {
              eqpStatusStat.value[eqpId] = [el];
            }
          });
        }
      }
    } catch (error) {
      console.error("获取设备状态数据报错", error);
    }
  }
}
watch([flattenTreeData, flattenData, comImageList], () => {
  if (!isObjEmpty(flattenTreeData.value) && !isObjEmpty(flattenData.value) && comImageReady.value) {
    if (middleTmp.length > 0) {
      let middle = [];
      middleTmp.forEach(el => {
        const { item, rawData } = el;
        const { propValue } = item;

        if (propValue && propValue.routerKey) {
          const el = flattenTreeData.value[propValue.routerKey];
          if (el) {
            const { className: itemClassName } = el;
            if (!itemClassName || globalClassName.includes(itemClassName)) {
              middle.push({ item, rawData });
            }
          }
        } else {
          middle.push({ item, rawData });
        }
      });
      middleComp.value = middle;
    }
  }
});
const setComp = computed(() => {
  let str = "FAC BUILD FLOOR ROOM";
  if (pageType.value === "ROOM") return modules["FLOOR"];
  else if (pageType.value === "MONITOR") {
    return modules["MONITOR"];
  } else if (str.indexOf(pageType.value) === -1) return modules["FLOOR"];

  return modules[pageType.value];
});

function updateScale(val) {
  scale.value = val;
}

function wsCallback(data) {
  if (data) {
    try {
      let wsdata = data;
      for (let key in wsdata) {
        if (flattenData.value) {
          const tag_vm = flattenData?.value[key];
          if (tag_vm) {
            tag_vm.value = wsdata[key];
          }
        }
      }
      eventBus.emit("wsUpdata", wsdata);
    } catch (error) {
      console.error(error);
    }
  }
}
async function queryDataByType(type, data) {
  const { facCode, positionCode } = data;
  getCounts(type);
  let classList = JSON.parse(localStorage.getItem("classList"));
  classList = pluck(classList, "code");
  if (type === "FAC" && queryFactoryData) {
    // const formData = new FormData();
    // formData.append("facCode", facCode);

    return queryFactoryData({ ...data, classList });
  } else if (type === "BUILD") return queryBuildData({ ...data, classList });
  else if (type === "FLOOR") {
    return queryFloorData({ ...data, classList });
  } else if (type === "ROOM" || type === "AREA") {
    try {
      const sensorRes = await queryErcAlarmLatestList({ twinId: positionCode });
      if (sensorRes) {
        sensorRoomVal.value = flattenDataByKeys(sensorRes, "eqpId");
      }
      const tempAndHumidRes = await queryTempAndHumid({ facCode: facCode, positionCode: positionCode });
      if (tempAndHumidRes) {
        tempAndHumidSource.value = tempAndHumidRes;
      }
    } catch (e) {
      console.log("e--->报警接口，温湿度传感器接口疑似", e);
    }
    return queryRoomData({ ...data, classList });
  } else {
    return visualqueryById({ eqpId: data.positionCode, classList });
  }
}
async function getCounts(type) {
  if (!["FLOOR", "FAC", "BUILD"].includes(type)) return;
  let data: Record<string, string> = { floorId: positionCode.value };
  if (type == "FAC") data = { factoryId: positionCode.value };
  if (type == "BUILD") data = { buildingId: positionCode.value };
  try {
    const alarmRes = await alarmRoomCount(data);
    if (alarmRes) {
      alarmRoomCounts.value = flattenDataByKeys(alarmRes, "twinId");
    }
  } catch (e) {
    console.log("e--->报警数量接口疑似", e);
  }
}
function mergeToCamelCase(str1, str2) {
  // 将字符串转换为小写并分割成单词数组
  let words1 = str1.toLowerCase().split(" ");
  let words2 = str2.toLowerCase().split(" ");

  // 合并两个数组，确保第一个单词的首字母小写，其余单词首字母大写
  let combinedWords = [...words1, ...words2].map((word, index) => {
    return index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1);
  });

  // 将处理后的单词数组合并成一个驼峰式字符串
  return combinedWords.join("");
}
async function queryAllTree(forceRefresh = false) {
  const lSItem = `visual_index_router_tree_${facCode.value}`;

  treeData.value = JSON.parse(await getItem(lSItem, "{}"));
  if (isObjEmpty(treeData.value) || route.query.noCache || forceRefresh) {
    treeData.value = await queryVisualTree({ facCode: facCode.value, needEqp: true });
    flattenTreeData.value = flattenDataByKeys(treeData.value, "code");
    try {
      await setItem(lSItem, JSON.stringify(treeData.value), 30, "m");
      // localStorage.setItem(lSItem, JSON.stringify(treeData.value));
    } catch (error) {
      console.log(error);
    }
  } else {
    try {
      const tree = treeData.value;
      if (tree[0]?.code == facCode.value) {
        flattenTreeData.value = flattenDataByKeys(treeData.value, "code");
      }
    } catch (error) {}
  }
  // treeData.value = await queryVisualTree({ facCode: facCode.value, needEqp: true });
  // flattenTreeData.value = flattenDataByKeys(treeData.value, "code");
  if (!isObjEmpty(flattenTreeData.value)) {
    // if (globalClassName !== "ADMIN") {
    //   routerTreeData.value = filterTree([flattenTreeData.value[facCode.value]], { className: globalClassName, type: "FLOOR" });
    // } else {
    //   routerTreeData.value = [flattenTreeData.value[facCode.value]];
    // }
    routerTreeData.value = filterTree([flattenTreeData.value[facCode.value]], "ROOM", { className: globalClassName });
  }
  // await dealDotAttrsShowInRoom(flattenTreeData.value);
  // done.value = true;
}
function filterTree(tree, type, filter) {
  return tree
    .map(node => {
      if (node.type !== type) {
        // 非指定 type 的节点，原样保留
        return { ...node, children: node.children ? filterTree(node.children, type, filter) : undefined };
      }

      let match = true;
      for (const key in filter) {
        if (node[key]) {
          if (Array.isArray(filter[key])) {
            if (!filter[key].includes(node[key])) {
              match = false;
              break;
            }
          } else if (node[key] !== filter[key]) {
            match = false;
            break;
          }
        }
      }

      if (match) {
        const newNode = { ...node };
        if (node.children) {
          newNode.children = filterTree(node.children, type, filter);
        }
        return newNode;
      }

      return null; // 被筛掉的节点
    })
    .filter(node => node !== null); // 过滤掉 null 节点
}

async function dealDotAttrsShowInRoom(flattenTreeData = {}) {
  if (positionCode.value && positionCode?.value.indexOf("ROOM") !== -1) {
    let dataList = [];
    let groupMap = {};
    let curData = flattenTreeData[positionCode.value];
    if (curData && curData.children) {
      for (let i = 0; i < curData.children.length; i++) {
        let item = curData.children[i];
        const { groupCode, showAttrInRoom, code: eqpId } = item;
        // if (showAttrInRoom) {
        let data = { eqpId };
        if (groupCode) {
          data["groupCode"] = groupCode;
          if (!groupMap[eqpId]) {
            groupMap[eqpId] = groupCode;
          }
        }
        dataList.push(data);
        // }
      }
    }
    if (dataList.length > 0) {
      let mapping = {};
      const res = await queryAttrsByEqpIds({ factoryId: facCode.value, dataList });
      if (res && res.length > 0) {
        for (let i = 0; i < res.length; i++) {
          let { attrs, eqpId } = res[i];
          let groupCode = groupMap[eqpId];
          showAttrsInRoom.value[eqpId] = [];

          if (groupCode) {
            if (!showAttrsInRoom.value[groupCode]) {
              showAttrsInRoom.value[groupCode] = [];
            }
          }
          attrs?.forEach(item => {
            const { positionNum: tagNum, attributeValue: value, valueUnit: unit, attributeName: title } = item;
            let el = {
              tagNum,
              value,
              unit,
              title
            };
            mapping[tagNum] = el;
            showAttrsInRoom.value[eqpId].push(el);
            if (groupCode) {
              showAttrsInRoom.value[groupCode].push(el);
            }
          });
        }
        Object.assign(flattenData.value, mapping);
      }
    }
  }
}
function isEquipment(code) {
  let strArr = ["FAC", "BUILD", "FLOOR", "ROOM", "AREA"];
  if (!code) return false;
  for (let val of strArr) {
    if (code.indexOf(val) !== -1) return false;
  }
  return true;
}
async function getCompData({ positionCode = null, className = null, type: routerPageType = null }) {
  // console.log(router);
  //获取配置页面拖拽的组件数据

  let compConfig = null;

  if (routerPageType === "EQP" || (!routerPageType && isEquipment(positionCode))) {
    const eqpData = await queryEqpId({ eqpId: positionCode });
    if (eqpData) {
      const { eqpId } = eqpData;
      let twinsId = eqpId;
      compConfig = await queryTemplData({ twinsId: twinsId });
    }
  } else {
    compConfig = await queryTemplData({ twinsId: positionCode });
  }
  if (!compConfig) {
    PxMessage.warning("当前页面暂未配置，敬请期待");

    if (!preview.value) {
      router.go(-1);
    }
    return false;
  }
  const json = JSON.parse(compConfig?.json);

  const { facCode, type } = compConfig;
  pageType.value = type;
  // console.log("json", json);
  //获取页面数据
  queryData.value = await queryDataByType(type, { positionCode, facCode, className });

  // 数据扁平化
  flattenData.value = flattenDataByKeys(queryData.value, "uniqueName tagNum");
  // await dealDotAttrsShowInRoom(flattenTreeData.value);
  // console.log(queryData.value);
  //合并真实数据与配置数据,暂时屏蔽该功能，因为没有真实点位如果这么处理会导致实际点位进不来
  // mergeCompDataAndConfig(flattenData.value, json);
  // console.log("mergeData", queryData.value);

  let middle: any[] = [],
    bottom: any[] = [],
    right: any[] = [],
    widgetVertical: any[] = [],
    widgetHorizontal: any[] = [],
    widgetVerticalLeft: any[] = [],
    left: any[] = [];
  let vImages = [];
  let [group, comps] = partitionArrayByValue(json, "component", "Group");
  flattenByIdData.value = flattenDataByKeys(json, "id");

  group.forEach(item => {
    const { conditionFilter, style } = item;
    const { display, visibility } = style;
    item.propValue.components.forEach(comp => {
      if (conditionFilter) {
        comp.conditionFilter = comp.conditionFilter ? `${comp.conditionFilter} ${conditionFilter}` : conditionFilter;
      }
      comp.style.display = display;
      comp.style.visibility = visibility;
      comps.push(comp);
    });
  });
  const haveHseData = flattenData.value["INTEGRATED_MONITORING"];
  if (haveHseData && haveHseData.children?.length > 0) {
    if (pageType.value === "FLOOR") {
      const haveHSEComp = comps.find(item => {
        const { dataBinding } = item;
        if (dataBinding?.type === "INTEGRATED_MONITORING") {
          return true;
        }
        return false;
      });
      const filterComp = comps.find(item => {
        const { component } = item;
        if (component === "DepFilter") {
          return true;
        }
        return false;
      });
      if (filterComp) {
        filterComp.propValue["hasHse"] = true;
      }
      if (!haveHSEComp) {
        comps.push(carbon);
        flattenByIdData.value[carbon.id] = carbon;
      }
    }
  }
  if (facCode === "FAC_93abf6" && ["FAC", "EQP"].includes(pageType.value) !== null) {
    let compList = flattenDataByKeys(componentList, "component");
    queryData.value.forEach((item, index) => {
      const { frontComponent, uniqueName, name, className, children, attrs } = item;
      const mapItem = compMap[frontComponent];
      if (mapItem) {
        const { value, config } = mapItem;
        let comp = cloneDeep(compList[value]);
        const dataBinding = {
          type: uniqueName,
          path: "",
          filter: "",
          val: {
            label: name,
            value: {
              uniqueName: uniqueName,
              name: name,
              children,
              attrs
            },
            id: uniqueName
          }
        };
        if (comp.dataAliase.contentList) {
          if (attrs?.length) comp.dataAliase.contentList = "attrs";
          else if (children?.length) comp.dataAliase.contentList = "children";
        }
        if (comp) {
          if (comp.component !== "TableAlert") {
            comp.id = uniqueName;
            comp.dataBinding = dataBinding;
            comp.style.top = index;
            comp.classConfig.className = className;
            comps.push(comp);
            flattenByIdData.value[comp.id] = comp;
          } else {
            const tableAlertComponent = comps.find(comp => comp.component === "TableAlert");
            comp.dataAliase.tableData = "children";
            comp.dataAliase.title = "name";
            if (tableAlertComponent) {
              tableAlertComponent.id = uniqueName;
              tableAlertComponent.dataBinding = dataBinding;
              tableAlertComponent.style.top = index;
              tableAlertComponent.classConfig.className = className;
              flattenByIdData.value[tableAlertComponent.id] = tableAlertComponent;
            } else {
              comp.id = uniqueName;
              comp.dataBinding = dataBinding;
              comp.style.top = index;
              comp.classConfig.className = className;
              comps.push(comp);
              flattenByIdData.value[comp.id] = comp;
            }
          }
        }
      }
    });
  }
  comps.forEach(item => {
    let rawData = flattenData.value[item.dataBinding?.type];
    //如果不在后台发送的数据里则证明该组件不需要后台数据，则直接返回空
    rawData = rawData ? rawData : {};
    if (item.component === "VImage") {
      const { propValue } = item;
      if (propValue && propValue.name) {
        vImages.push(propValue.name);
      }
    }
    if (item.belong === "middle") {
      // const { propValue } = item;

      // if (propValue && propValue.routerKey) {
      //   const el = flattenTreeData.value[propValue.routerKey];
      //   if (el) {
      //     const { className: itemClassName } = el;
      //     if (!itemClassName || globalClassName.includes(itemClassName)) {
      //       middle.push({ item, rawData });
      //     }
      //   }
      // } else {
      //   middle.push({ item, rawData });
      // }
      middleTmp.push({ item, rawData });
    } else if (item.belong === "bottom") {
      bottom.push({ item, rawData });
    } else if (item.belong === "right") {
      const { classConfig, component } = item;
      if (preview.value && component === "equipRouter") {
        return;
      }
      if (classConfig) {
        const { className: itemClassName } = classConfig;
        if (!itemClassName || globalClassName.includes(itemClassName) || itemClassName === "HSE") {
          right.push({ item, rawData });
        }
      } else {
        right.push({ item, rawData });
      }
    } else if (item.belong === "left") {
      left.push({ item, rawData });
    } else if (item.belong === "widgetVertical") {
      if (item.component == "DepFilter") {
        if (item.propValue) {
          const { excludes } = item.propValue;
          if (excludes && isExcluded(excludes, globalClassName)) {
            widgetVertical.push({ item, rawData });
          }
        }
      } else widgetVertical.push({ item, rawData });
    } else if (item.belong === "widgetHorizontal") {
      widgetHorizontal.push({ item, rawData });
    } else if (item.belong === "widgetVerticalLeft") {
      widgetVerticalLeft.push({ item, rawData });
    }
  });
  //右侧组件按照拖拽的top值进行从上到下的排序
  right.sort((a, b) => a["item"].style.top - b["item"].style.top);
  bottom.sort((a, b) => a["item"].style.left - b["item"].style.left);
  if (vImages && vImages.length > 0) {
    let res = await downloadPic({ originNameList: ensurePngSuffix(vImages), moduleName: "twins_visualization" });
    if (res?.length) {
      comImageList.value = flattenDataByKeys(res, "originalName");
    }
  }
  comImageReady.value = true;

  // middleComp.value = middle;
  bottomComp.value = bottom;
  rightComp.value = right;
  leftComp.value = left;

  nextTick(() => {
    widgetVerticalComp.value = widgetVertical;
    widgetHorizontalComp.value = widgetHorizontal;
    widgetVerticalCompLeft.value = widgetVerticalLeft;
  });

  //获取巡检信息
  if (!isInspection.value && pageType.value == "FAC") {
    inspectionList.value = (await queryInspectionList({ routeName: "" })) as Array<any>;
  }
}
function partitionArrayByValue(array, key, value) {
  // 初始化两个空数组，用于存储结果
  const equals = [];
  const notEquals = [];

  // 遍历数组，根据条件分配到相应的数组中
  array.forEach(item => {
    if (item[key] === value) {
      equals.push(item);
    } else {
      notEquals.push(item);
    }
  });

  // 返回包含两个数组的对象
  return [equals, notEquals];
}

const changeStyle = ({ styleName, value, compId }) => {
  let findComp = null;
  try {
    findComp = flattenByIdData.value ? flattenByIdData.value[compId] : null;
    if (findComp) {
      if (findComp.style[styleName] == undefined) {
        Reflect.set(findComp.style, styleName, value);
      } else {
        findComp.style[styleName] = value;
      }
    }
  } catch (e) {
    console.error("changeStyle报错", e);
  }
};

const showOrHideLayer = compId => {
  const comp = flattenByIdData.value ? flattenByIdData.value[compId] : null;
  if (comp) {
    const isVisible = Reflect.get(comp.style, "visibility") === "visible";
    const isBlock = Reflect.get(comp.style, "display") === "block";

    Reflect.set(comp.style, "visibility", isVisible ? "hidden" : "visible");
    Reflect.set(comp.style, "display", isBlock ? "none" : "block");
  }
};

onMounted(async () => {
  if (!isTreeQuery) {
    isTreeQuery = true;
    queryAllTree();
  }
  // 监听事件处理子孙组件发来的改变组件样式的请求，这个未来是不是收录到useEvent比较好，useEvent接收事件列表进行初始化
  eventBus.on("changeStyle", changeStyle);
  eventBus.on("showOrHideLayer", showOrHideLayer);
});

onUnmounted(() => {
  eventBus.off("changeStyle", changeStyle);
  eventBus.off("showOrHideLayer", showOrHideLayer);
});

// 加防抖出现数据不同步问题，把问题复杂化了到出现性能问题再进行优化
// let timer = null;

// function handleScaleChange(pre, cur) {
//   clearTimeout(timer);

//   timer = setTimeout(() => {
//     changeComponentsSizeWithScale(middleComp.value, pre, cur);
//   }, 1000);
// }

// 面包屑路由跳转
function breadcrumbClick(data) {
  try {
    PxMessage.closeAll();
  } catch (error) {
    console.error(error);
  }
  let query: any = {
    compEmitData: data
  };
  if (typeof data === "object") {
    query = {
      compEmitData: data.code,
      type: data.type
    };
  }
  if (isInspection.value) {
    inspectionHandle(query.compEmitData, true);
    return;
  }
  router.push({
    path: "/all/visual/template",
    query
  });
}
function breadcrumbBack() {
  const prePath = router.options.history.state.back as string;
  if (prePath.indexOf("visual/template") !== -1) {
    router.back();
  } else if (pageType.value === "MONITOR") {
    router.replace({
      path: "/redirect/all/visual/template"
    });
  }
}
async function inspectionHandle(val, fromRouter = false) {
  const path = "/all/visual/template";
  let data: any = {
    path, //打开巡检页面
    query: {
      routeCode: val
    }
  };
  if (fromRouter) {
    data.query = {
      //正常可视化页面打开
      compEmitData: val
    };
  }
  const newpage = router.resolve(data);
  window.open(newpage.href, "_blank"); // 打开新的窗口(跳转路径，跳转类型)
}
async function dealInspection(val) {
  const inspectionItem = (await queryInspectionItem({ routeCode: val })) as Array<any>;
  if (inspectionItem && inspectionItem.length > 0) {
    segments.value = inspectionItem.map(item => ({
      name: item.itemName,
      twinId: item.itemCode,
      duration: item.playTime ? item.playTime : 60,
      type: item.itemType,
      remark: item.remark
    }));

    loadInspectionData(0, true);
  } else {
    isInspectionEmpty.value = true;
    done.value = true;
  }
  console.log(val);
}
async function handleEnd(index) {
  console.log("⏹️ End of item:", index);
  let next = index + 1;
  if (next < segments.value.length) {
    loadInspectionData(next);
  } else {
    loadInspectionData(0);
  }
}

// async function handlePrev(index) {
//   loadInspectionData(index, true);
// }
// async function handleNext(index) {
//   console.log("⚙️ Preload recommended for:", index);
//   loadInspectionData(index, true);
// }
async function handleItemChange(index) {
  loadInspectionData(index, true);
}
async function loadInspectionData(index, isInit = false) {
  if (index >= segments.value.length) return;
  start();
  curInspectionIndex.value = index;
  const item = segments.value[index];
  const { twinId, type, remark, duration } = item;
  monitorPlayTime.value = duration;
  positionCode.value = twinId;
  if (type !== "ROOM") {
    monitorDialogShow.value = false;
  }
  reset();
  pageType.value = type;
  if (type === "MONITOR") {
    cameraItem.value = item;
  } else {
    await getCompData({ positionCode: twinId, type });
  }
  nextTick(() => {
    if (isInit) {
      player.value.play();
      isInspection.value = true;
    } else {
      player.value.continueAfterLoading();
    }
    if (type === "ROOM") {
      monitorDialogShow.value = true;
    }
  });
}
// 用于巡检置空数据
function reset() {
  leftComp.value = [];
  middleComp.value = [];
  bottomComp.value = [];
  widgetVerticalComp.value = [];
  widgetVerticalCompLeft.value = [];
  widgetHorizontalComp.value = [];
  rightComp.value = [];
  queryData.value = null;
  flattenData.value = null;
  flattenByIdData.value = null;
  pageType.value = "";
  // positionCode.value = "";

  toggleTree.value = false;
  eqpStatusStat.value = {};

  alarmRoomCounts.value = null;
  sensorRoomVal.value = null;
  tempAndHumidSource.value = null;
  showAttrsInRoom.value = {};
  done.value = false;
  pipeName.value = "";

  middleTmp = [];
  comImageReady.value = true;
  // segments.value = [];
  // monitorPlayTime.value = 60;
  // inspectionList.value = [];
  // isInspection.value = false;
  // cameraItem.value = null;
  setTimeout(() => {
    if (!done.value) {
      console.error("处理loading不消失问题，可能巡检摄像头页面重复点击");
      done.value = true;
    }
  }, 4000);
}
/**
 * 根据指定键从对象数组中提取对应值，发生任何错误时返回空数组。
 * @param {any} arr - 要处理的数组
 * @param {string} key - 要提取的键
 * @returns {Array} 提取出的值数组，出错时返回 []
 */
function pluck(arr, key) {
  try {
    // 不是数组或 key 不是字符串，直接返回空数组
    if (!Array.isArray(arr) || typeof key !== "string") {
      return [];
    }
    // 使用 reduce 一次遍历完成提取并过滤不存在的键
    return arr.reduce((result, item) => {
      if (item != null && typeof item === "object" && key in item) {
        result.push(item[key]);
      }
      return result;
    }, []);
  } catch (e) {
    // 捕获任何运行时错误，保证稳健性
    return [];
  }
}
function refershTree() {
  queryAllTree(true);
}
function handleInspectionEmpty() {
  router.replace({
    path: "/all/visual/inspection"
  });
}
</script>

<template>
  <div v-loading="!done" element-loading-text="页面加载中..." class="template-page select-none">
    <Breadcrumb
      v-if="!preview && !isInspectionEmpty"
      v-model:toggle-tree="toggleTree"
      class="breadcrumb"
      :positionCode="positionCode"
      :tree-data="flattenTreeData"
      :cameraItem="cameraItem"
      @breadcrumb-click="breadcrumbClick"
      @back="breadcrumbBack"
    />
    <RouterTree
      v-if="!preview && pageType != 'MONITOR'"
      :toggle-tree="toggleTree"
      :flattenTreeData="flattenTreeData"
      :positionCode="positionCode"
      :tree-data="routerTreeData"
      @router-click="breadcrumbClick"
      @refresh-tree="refershTree"
    />
    <template v-if="queryData || pageType === 'MONITOR'">
      <component
        :is="setComp"
        v-if="!isInspection"
        v-model:done="done"
        :middleComp="middleComp"
        :leftComp="leftComp"
        :widgetVerticalComp="widgetVerticalComp"
        :widgetVerticalCompLeft="widgetVerticalCompLeft"
        :bottomComp="bottomComp"
        :rightComp="rightComp"
        :widgetHorizontalComp="widgetHorizontalComp"
        :inspectionList="inspectionList"
        :cameraItem="cameraItem"
        :preview="preview"
        @inspectionHandle="inspectionHandle"
      />
      <component
        :is="setComp"
        v-else
        :key="curInspectionIndex"
        v-model:done="done"
        :middleComp="middleComp"
        :leftComp="leftComp"
        :widgetVerticalComp="widgetVerticalComp"
        :widgetVerticalCompLeft="widgetVerticalCompLeft"
        :bottomComp="bottomComp"
        :rightComp="rightComp"
        :widgetHorizontalComp="widgetHorizontalComp"
        :inspectionList="inspectionList"
        :cameraItem="cameraItem"
        @inspectionHandle="inspectionHandle"
      />
    </template>

    <TimelinePlayer
      v-if="!preview"
      v-show="isInspection"
      ref="player"
      :items="segments"
      :preload-threshold="2"
      :loop="true"
      @onItemEnd="handleEnd"
      @onItemChange="handleItemChange"
    />
    <MonitorDialog
      ref="monitor"
      v-model:is-show="monitorDialogShow"
      :position-code="positionCode"
      :is-inspection="isInspection"
      :play-time="monitorPlayTime"
    />
    <div v-if="isInspectionEmpty" class="inspection-empty">
      <px-empty description="请先配置巡检位置再进行查看" />
      <px-button type="primary" @click="handleInspectionEmpty">巡检路线设定</px-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.template-page {
  position: relative;
  overflow: hidden;

  .breadcrumb {
    position: absolute;
    z-index: 99;
  }

  .inspection-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }
}
</style>
